/**
 * 当RFID在有网情况下的同步逻辑
 */
import sqlLite from '../../common/sqllite-utils';
/**
 * 暴露同步函数，当点击同步按钮
 */
export function onClickSynchronousButton() {
  function filterObjKeys(obj, keys) {
    return Object.keys(obj).reduce((newData, key) => {
      if (!keys.includes(key)) {
        newData[key] = obj[key];
      }
      return newData;
    }, {});
  }

  // 开启数据库
  sqlLite.openSqllite()
    .then((e) => {
      if (JSON.stringify(e) === '{}') {
        console.log('成功的开启数据库');
      }
    })
    .catch((err) => {
      console.log(err, '开启数据库失败回调');
    });

   /**
    * 请求菜单参数
    */
   this.$u.api.getMenuList({page: 1,pageSize: 15}).then(res => {
     if(res.code === 0) {
       const menuList = res.data.list
       uni.setStorage({
         key: "menulist",
         data: menuList,
       });
       this.functionbuttondata = uni.getStorageSync("menulist")
       console.log(this.functionbuttondata,'44444444444444444444444444444444444444444444444444444')
     }
   })
   
  /**
   * 建立装备类型表
   */
  sqlLite.executeSqlCode(
  				'create table if not exists userInfos ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"name" TEXT)',
  			).then((e) => {
    console.log(e, '建表成功回调');
    /**
     * 请求装备类型表数据
     */
    const query = {
      page: 1,
      pageSize: 1000,
    };
    this.$u.api.queryingDeviceModel(query).then((res) => {
      console.log(res);
      if (res.data.list.length >= 0) {
        sqlLite.executeSqlCode(
           	'DELETE FROM userInfos',
        ).then((res) => {
          console.log(res, '删除数据成功回调');
        });
        for (let i = 0; i < res.data.list.length; i++) {
          sqlLite.executeSqlCode(
           	`insert into userInfos (id,name) values ("${res.data.list[i].id}","${res.data.list[i].name}")`,
          );
        }
      } else {
        /**
            * 当得到的数据为空
            */
      }
      /**
          * 应用此数据给页面
          */
      const tableName = 'userInfos';
      sqlLite.selectFromTable(
         	`select * from ${tableName}`,
      ).then((res) => {
        console.log(res, '本地数据库装备类型表的数据');
        this.$u.vuex('typeList', res);
      });
    });
  }).catch((e) => {
    console.log(e, '失败');
  });

  /**
 * 建立装备名称表
 */
  sqlLite.executeSqlCode(
  				'create table if not exists equipmentNameTables ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"name" TEXT,"hb_rock_zhuang_fen_lei_id" TEXT)',
  			).then((e) => {
    console.log(e, '建立装备名称表成功');
    const query = {
      page: 1,
      pageSize: 1000,
    };
    this.$u.api.accessToEquipmentName(query).then((res) => {
      // console.log(res.data.list, '得到的装备名称接口数据！');
      if (res.data.list.length >= 0) {
        sqlLite.executeSqlCode(
                 	'DELETE FROM equipmentNameTables',
        ).then((res) => {
          console.log(res, '装备名称表删除数据成功回调');
        });
        for (let i = 0; i < res.data.list.length; i++) {
          sqlLite.executeSqlCode(
                 	`insert into equipmentNameTables (id,name,hb_rock_zhuang_fen_lei_id) values ("${res.data.list[i].id}","${res.data.list[i].name}","${res.data.list[i].hb_rock_zhuang_fen_lei_id}")`,
          );
        }
        const tableName = 'equipmentNameTables';
        sqlLite.selectFromTable(
                 	`select * from ${tableName}`,
        ).then((res) => {
          console.log(res, '本地数据库装备名称表数据');
          this.$u.vuex('nameList', res);
          // 此处相当于多复制一层数据，利于筛选时使用
          this.$u.vuex('namelist', res);
        });
      }
    });
  });

  /**
 * 建立货架表
 */
  sqlLite.executeSqlCode(
  				'create table if not exists shelf ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"shelfname" TEXT)',
  			).then((e) => {
    console.log(e, '建立货架表成功！');
    const query = {
      page: 1,
      pageSize: 1000,
    };
    this.$u.api.shelvesQuery(query).then((res) => {
      console.log(res, '货架查询接口的数据');
      if (res.data.list.length >= 0) {
        sqlLite.executeSqlCode(
                 	'DELETE FROM shelf',
        ).then((res) => {
          console.log(res, '删除货架表成功回调！');
        });
        for (let i = 0; i < res.data.list.length; i++) {
          sqlLite.executeSqlCode(
                 	`insert into shelf (id,shelfname) values ("${res.data.list[i].id}","${res.data.list[i].code}")`,
          );
        }
        const tableName = 'shelf';
        sqlLite.selectFromTable(
                 	`select * from ${tableName}`,
        ).then((res) => {
          this.$u.vuex('shelvesList', res);
          console.log(res, '本地数据库货架表的数据！');
        });
      }
    });
  });

  /**
 * 建立单位表
 */
  sqlLite.executeSqlCode(
  				'create table if not exists units ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"unitname" TEXT)',
  			).then((e) => {
    console.log(e, '建立单位表成功！');
    const query = {
      page: 1,
      pageSize: 1000,
    };
    this.$u.api.unitTheQuery(query).then((res) => {
      console.log(res, '单位查询接口数据');
      if (res.data.length >= 0) {
        sqlLite.executeSqlCode(
                 	'DELETE FROM units',
        ).then((res) => {
          console.log(res, '删除单位表成功回调！');
        });
        for (let i = 0; i < res.data.length; i++) {
          sqlLite.executeSqlCode(
                 	`insert into units (id,unitname) values ("${res.data[i].dept_id}","${res.data[i].dept_name}")`,
          );
        }
        const tableName = 'units';
        sqlLite.selectFromTable(
                 	`select * from ${tableName}`,
        ).then((res) => {
          this.$u.vuex('unitList', res);
          console.log(res, '本地数据库单位表的数据！');
        });
      }
    });
  });


  /**
 * 建立来源表
 */
  sqlLite.executeSqlCode(
    				'create table if not exists sourceTable ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"sourcename" TEXT)',
    			).then((e) => {
    console.log(e, '建立装备来源表成功！');
    const query = {
      page: 1,
      pageSize: 1000,
    };
    this.$u.api.equipmentSourceQuery(query).then((res) => {
      console.log(res, '装备来源接口数据');
      if (res.data.list.length >= 0) {
        sqlLite.executeSqlCode(
                   	'DELETE FROM sourceTable',
        ).then((res) => {
          console.log(res, '删除来源表成功回调！');
        });
        for (let i = 0; i < res.data.list.length; i++) {
          sqlLite.executeSqlCode(
                   	`insert into sourceTable (id,sourcename) values ("${res.data.list[i].id}","${res.data.list[i].name}")`,
          );
        }
        const tableName = 'sourceTable';
        sqlLite.selectFromTable(
                   	`select * from ${tableName}`,
        ).then((res) => {
          this.$u.vuex('sourceList', res);
          console.log(res, '本地数据库来源表的数据！');
        });
      }
    });
  });

  /**
 * 创建库室表
 */
  sqlLite.executeSqlCode(
  				'create table if not exists libraryRoomTable ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"libraryroomname" TEXT)',
  			).then((e) => {
    console.log(e, '建立库室表成功！');
    const query = {
      page: 1,
      pageSize: 1000,
    };
    this.$u.api.accessToLibraryRoom(query).then((res) => {
      console.log(res, '库室接口数据');
      if (res.data.list.length >= 0) {
        sqlLite.executeSqlCode(
                 	'DELETE FROM libraryRoomTable',
        ).then((res) => {
          console.log(res, '删除库室表成功回调！');
        });
        for (let i = 0; i < res.data.list.length; i++) {
          sqlLite.executeSqlCode(
                 	`insert into libraryRoomTable (id,libraryroomname) values ("${res.data.list[i].id}","${res.data.list[i].name}")`,
          );
        }
        const tableName = 'libraryRoomTable';
        sqlLite.selectFromTable(
                 	`select * from ${tableName}`,
        ).then((res) => {
          this.$u.vuex('libraryRoomList', res);
          console.log(res, '本地数据库室表的数据！');
        });
      }
    });
  });

  /**
   * 创建装备入库同步表，该表通过查询接口，插入本地数据库
   */
  sqlLite.executeSqlCode(
    				'create table if not exists Synchronoustables ("id" INTEGER,"hb_rock_ku_shi_id" INTEGER,"hb_rock_zhuangxh_id" INTEGER,"lai_yuan_id" INTEGER,"rfid" TEXT,"shelves_id" INTEGER,"allotmentTime" TEXT,"over_time" TEXT,"wuping_name" TEXT,"hb_rock_ku_shi_name" TEXT,"xin_hao" TEXT,"sta_name" TEXT,"hb_rock_zhuang_fen_lei_name" TEXT)',
    			).then((res) => {
    console.log(res, '建立装备入库同步表成功');
    const query = {
      page: 1,
      pageSize: 1000,
      sta: 10,
    };
    this.$u.api.accessToDataWarehous(query).then((res) => {
      // console.log(res, '获取到的装备入库同步表数据，，，，，，，，，，，，');
      if (res.data.list.length >= 0) {
        sqlLite.executeSqlCode(
                   	'DELETE FROM Synchronoustables',
        ).then((res) => {
          console.log(res, '删除装备入库同步表成功回调！');
        });
        sqlLite.executeSqlCode('BEGIN;')
        for (let i = 0; i < res.data.list.length; i++) {
          sqlLite.executeSqlCode(
                   	`insert into Synchronoustables (id,hb_rock_ku_shi_id,hb_rock_zhuangxh_id,lai_yuan_id,rfid,shelves_id,allotmentTime,over_time,wuping_name,hb_rock_ku_shi_name,xin_hao,sta_name,hb_rock_zhuang_fen_lei_name) values ("${res.data.list[i].id}","${res.data.list[i].hb_rock_ku_shi_id}","${res.data.list[i].hb_rock_zhuangxh_id}","${res.data.list[i].lai_yuan_id}","${res.data.list[i].rfid}","${res.data.list[i].shelves_id}","${res.data.list[i].allotmentTime}","${res.data.list[i].over_time}","${res.data.list[i].wuping_name}","${res.data.list[i].hb_rock_ku_shi_name}","${res.data.list[i].xin_hao}","${res.data.list[i].sta_name}","${res.data.list[i].hb_rock_zhuang_fen_lei_name}")`,
          ).then().catch(err => console.log(err))
        }
        sqlLite.executeSqlCode('COMMIT;')
        const tableName = 'Synchronoustables';
        sqlLite.selectFromTable(
                   	`select * from ${tableName}`,
        ).then((res) => {
          // console.log(res, '本地数据库装备入库同步表的数据！?????????????????????????????????????????');
        }).catch((err) => '查找本地数据装备入库同步表失败的回调？？？？？？？？？？？？？');
      }
    });
  });

/**
 * 创建历史记录维修装备维修
 */
    sqlLite.executeSqlCode(
      				'create table if not exists equipmentMaintenancetables ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"rfid" TEXT,"sta" INTEGER,"hb_rock_ku_shi_name" TEXT,"user_name" TEXT)',
      			).then((e) => {
      console.log(e, '建立装备维修表成功！');
      const query = {
        page: 1,
        pageSize: 1000,
      };
      this.$u.api.equipmentMaintenanceQuery(query).then((res) => {
        console.log(res, '装备维修表接口数据');
        if (res.data.list.length >= 0) {
          sqlLite.executeSqlCode(
                     	'DELETE FROM equipmentMaintenancetables',
          ).then((res) => {
            console.log(res, '删除装备维修表成功回调！');
          });
          for (let i = 0; i < res.data.list.length; i++) {
            sqlLite.executeSqlCode(
                     	`insert into equipmentMaintenancetables (id,rfid,sta,hb_rock_ku_shi_name,user_name) values ("${res.data.list[i].id}","${res.data.list[i].rfid}","${res.data.list[i].sta}","${res.data.list[i].hb_rock_ku_shi_name}","${res.data.list[i].user_name}")`,
            ).then(res => {
              console.log(res,'插入装备维修表成功的回调')
            }).catch(err => {
              console.log(err,'插入装备维修表失败的回调')
            })
          }
          const tableName = 'equipmentMaintenancetables';
          sqlLite.selectFromTable(
                     	`select * from ${tableName}`,
          ).then((res) => {
            console.log(res, '本地数据库装备维修表的数据++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++');
          }).catch(err => {
            console.log(err,'错误装备维修表的回调+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
          })
        }
      });
    });
    
  /**
   * 创建装备保养表equipmentkeepalivetable
   */
    sqlLite.executeSqlCode(
      				'create table if not exists equipmentkeepalivetable ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"rfid" TEXT,"sta" INTEGER,"hb_rock_ku_shi_name" TEXT,"user_name" TEXT)',
      			).then((e) => {
      console.log(e, '建立装备保养表成功！');
      const query = {
        page: 1,
        pageSize: 1000,
      };
      this.$u.api.equipmentkeepaliveQuery(query).then((res) => {
        console.log(res, '装备保养表接口数据');
        if (res.data.list.length >= 0) {
          sqlLite.executeSqlCode(
                     	'DELETE FROM equipmentkeepalivetable',
          ).then((res) => {
            console.log(res, '删除装备保养表成功回调！');
          });
          for (let i = 0; i < res.data.list.length; i++) {
            sqlLite.executeSqlCode(
                     	`insert into equipmentkeepalivetable (id,rfid,sta,hb_rock_ku_shi_name,user_name) values ("${res.data.list[i].id}","${res.data.list[i].rfid}","${res.data.list[i].sta}","${res.data.list[i].hb_rock_ku_shi_name}","${res.data.list[i].user_name}")`,
            ).then(res => {
              console.log(res,'插入装备保养表成功的回调')
            }).catch(err => {
              console.log(err,'插入装备保养表失败的回调')
            })
          }
          const tableName = 'equipmentkeepalivetable';
          sqlLite.selectFromTable(
                     	`select * from ${tableName}`,
          ).then((res) => {
            console.log(res, '本地数据库装备保养表的数据++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++');
          }).catch(err => {
            console.log(err,'错误装备保养表的回调+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
          })
        }
      });
    });
    
  /**
     * 创建临时装备入库表equipmentStorageTable
     */
  sqlLite.executeSqlCode(
    				'create table if not exists equipmentStorageTables ("hb_rock_ku_shi_id" INTEGER,"hb_rock_zhuangxh_id" INTEGER,"lai_yuan_id" INTEGER,"rfid" TEXT,"depid" INTEGER,"shelves_id" INTEGER,"allotmentTime" TEXT,"over_time" TEXT)',
    			).then((res) => {
    console.log(res, '装备入库表创建成功');
    const tableName = 'equipmentStorageTables';
    sqlLite.selectFromTable(
               	`select * from ${tableName}`,
    ).then((res) => {
      console.log(res,'0000000000000000')
      /**
               * 此时的数据用来进行对服务器进行同步操作，对该数据做第二次加工，去除掉其中的id属性
               */
      const deleteKeys = ['id'];
      const arr = [];
      for (let i = 0; i < res.length; i++) {
        const newObj = filterObjKeys(res[i], deleteKeys);
        console.log(newObj);
        arr.push(newObj);
      }
      console.log(arr,'树高要的数据！')
      this.$u.api.initialLibraryStorage(arr).then(res => {
        console.log(res,'成功的回调啊啊啊啊啊啊')
        if(res.code === 0) {
          sqlLite.executeSqlCode(
                     	'DELETE FROM equipmentStorageTables',
          ).then(res => {
            console.log(res,'已经成功同步至线上数据库，临时装备入库表已经没啥用了')
            
          }).catch(err=> {
            console.log(err,'删除数据库失败了！')
          })
        }
        
      }).catch(err => {
        console.log(err,'没有成功初次入库，这是错误的回调')
      })
    });
  });
  
  /**
   * 建立事由表，在同步过后，可以选择相关事由
   */
  sqlLite.executeSqlCode(
  				'create table if not exists reasonforwhytable ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"name" TEXT)',
  			).then((e) => {
    console.log(e, '建立事由表成功！');
    const queryreason = {
      page: 1,
      pageSize: 1000,
      hb_rock_ku_shi_id: uni.getStorageSync("shiyouid")
    };
    this.$u.api.forWhyThings(queryreason).then((res) => {
      console.log(res, '事由表接口数据');
      if (res.data.list.length >= 0) {
        sqlLite.executeSqlCode(
                 	'DELETE FROM reasonforwhytable',
        ).then((res) => {
          console.log(res, '删除事由表成功回调！');
        });
        for (let i = 0; i < res.data.list.length; i++) {
          sqlLite.executeSqlCode(
                 	`insert into reasonforwhytable (id,name) values ("${res.data.list[i].id}","${res.data.list[i].name}")`,
          );
        }
        const tableName = 'reasonforwhytable';
        sqlLite.selectFromTable(
                 	`select * from ${tableName}`,
        ).then((res) => {
          
          this.$u.vuex('reasonForwhyList', res);
          console.log(res, '本地事由表的数据！');
        });
      }
    });
  });
  
/**
 * 创建出入库表，此表用来支持，平时出入库业务
 */
  // sqlLite.executeSqlCode(
  // 				'create table if not exists inOutTheLibraryTable("id" INT(10) PRIMARY KEY NOT NULL,"rfid" CHAR,"hb_rock_ku_shi_id" INTEGER,"hb_rock_ku_shi_name" CHAR,"hb_rock_zhuangxh_id" int,"wuping_name" CHAR,"xin_hao" CHAR)',
  // 			).then(res => {
  //         console.log('进出入库表创建成功！')
  //       })
  sqlLite.executeSqlCode(
    				'create table if not exists inoutTheLibraryTable ( "id" INTEGER PRIMARY KEY AUTOINCREMENT,"rfid" TEXT,"rfid" TEXT,"hb_rock_ku_shi_id" INTEGER,"hb_rock_ku_shi_name" TEXT,"hb_rock_zhuangxh_id" INTEGER,"wuping_name" TEXT,"xin_hao" TEXT)',
    			).then(res => {
            console.log(res,'成功创建出入库表')
            const tableName = 'inoutTheLibraryTable'
            sqlLite.selectFromTable(
                       	`select * from ${tableName}`,
            ).then(res => {
              console.log(res,'====================================================')
            }).catch(err => {
              console.log(err,'+++++++++++++++++++++++++++++++++++++++++++++++++++++++')
            })
            
          }).catch(err => {
          })
    
  /**
   * 创建陪同人表
   */
 
    sqlLite.executeSqlCode(
    				'create table if not exists accompanyingPersonTable ( "ID" INTEGER PRIMARY KEY AUTOINCREMENT,"nickName" TEXT)',
    			).then(res => {                 
                  this.$u.api.accessToAccompanyPeople({
                        page: 1,
                        pageSize: 1000
                      }).then(res => {
                        // console.log(res,'此处为获取到的陪同人数据哈哈哈')
                        if(res.data.list.length > 0) {
                          sqlLite.executeSqlCode(
                                   	'DELETE FROM accompanyingPersonTable',
                          ).then((res) => {
                            console.log(res, '删除陪同人表成功回调！');
                          }).catch(err => {
                            console.log(err,'删除陪同人表失败回调')
                          })
                          for(let i = 0; i < res.data.list.length; i++) {
                            sqlLite.executeSqlCode(
                                   	`insert into accompanyingPersonTable (ID,nickName) values ("${res.data.list[i].ID}","${res.data.list[i].nickName}")`,
                            );
                          }
                         const tableName = 'accompanyingPersonTable';
                         sqlLite.selectFromTable(
                                  	`select * from ${tableName}`,
                         ).then(res => {
                           // console.log(res,'本地数据库陪同人表的数据')
                         })
                        }
                      })
          })
          console.log('000000000000000000000000000000000000000000000000000000000000000000000000')
          const queryobj = {
            user_id:uni.getStorageSync('accompanyingPerson'),
            shi_you_id:uni.getStorageSync('reasonforwhyid'),
            hb_rock_ku_shi_id:uni.getStorageSync('shiyouid'),
            rfid_list:uni.getStorageSync('rfidlistarr')
          }
          this.$u.api.equipmentForInsOutsReason(queryobj).then(res => {
            console.log(res,'成功的结果')
            if(res.code === 0) {
              sqlLite.executeSqlCode(
                       	'DELETE FROM inoutTheLibraryTable',
              ).then((res) => {
                console.log(res, '删除进出入表成功回调！');
                uni.setStorage({
                  key: "rfidlistarr",
                  data: [],
                });
              });
            }
            
          }).catch(err => {
            console.log(err,'失败的结果')
          })
          
  /**
   * 调用盘点入库接口，向后台传入参数
   */
    const inventoryList = uni.getStorageSync('inventoryList')
    this.$u.api.inventoryReport(inventoryList).then(res => {
      console.log(res,'正确噜啦噜啦嘞绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿')
      if(res.code === 0) {
        uni.setStorage({
          key: "inventoryList",
          data: null,
        });
      }
    }).catch(err => {
      console.log(err,'错误噜啦噜啦嘞绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿绿 ')
    })
    
    /**
     * 同步群扫数据
     */
    const groupEsauqueryobj = {
      user_id:uni.getStorageSync('countaccompanyingPerson'),
      shi_you_id:uni.getStorageSync('reasonforwhyid'),
      hb_rock_ku_shi_id:uni.getStorageSync('shiyouid'),
      rfid_list:uni.getStorageSync('rfidList')
    }
    this.$u.api.equipmentForInsOutsReason(groupEsauqueryobj).then(res => {
      console.log(res,'成功的结果')
      if(res.code === 0) {
        sqlLite.executeSqlCode(
                 	'DELETE FROM inoutTheLibraryTable',
        ).then((res) => {
          console.log(res, '删除进出入表成功回调！');
          uni.setStorage({
            key: "rfidList",
            data: [],
          });
        });
      }
      
    }).catch(err => {
      console.log(err,'失败的结果')
    })
}
